package com.group9.repository.impl;

import com.group9.pojo.CommentMessage;
import com.group9.repository.CommentMessageRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;

import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * Created by Lcouncillor on 2020/6/9.
 */
@Repository
public class CommentMessageRepositoryImpl implements CommentMessageRepository {
    @Autowired
    MongoTemplate mongoTemplate;

    @Override
    public List<CommentMessage> selectNoReadMessageByReceiverId(String receiverId) {
        Query query = new Query();
        Criteria criteria = Criteria.where("receiver_id").is(receiverId).and("status").is(1);
        query.addCriteria(criteria);
        return mongoTemplate.find(query,CommentMessage.class,"comment_message");
    }

    @Override
    public List<CommentMessage> selectReadedMessageByReceiverId(String receiverId) {
        Query query = new Query();
        Criteria criteria = Criteria.where("receiver_id").is(receiverId).and("status").is(0);
        query.addCriteria(criteria);
        return mongoTemplate.find(query,CommentMessage.class,"comment_message");    }

    @Override
    public Integer insertCommentMessage(CommentMessage commentMessage) {
        mongoTemplate.save(commentMessage, "comment_message");
        return 1;
    }

    @Override
    public CommentMessage selectCommentMessageById(String messageId) {
        Query query = new Query();
        Criteria criteria = Criteria.where("id").is(messageId).and("status").is(1);
        query.addCriteria(criteria);
        return mongoTemplate.findOne(query,CommentMessage.class,"comment_message");

    }

    @Override
    public List<CommentMessage> selectByCommentIdAndUserId(String commentId, String receiverId) {
        Query query = new Query();
        Criteria criteria = Criteria.where("comment_id").is(commentId).and("receiver_id").is(receiverId).and("status").is(1);
        query.addCriteria(criteria);
        return mongoTemplate.find(query,CommentMessage.class,"comment_message");
    }

    @Override
    public Integer updateStatus(List<CommentMessage> commentMessages) {
        int result = 0;
        for (int i=0; i<commentMessages.size(); i++){
            commentMessages.get(i).setStatus(0);
            mongoTemplate.save(commentMessages.get(i), "comment_message");
            result++;
        }
        return result;
    }
}
